//
//  ExperienceViewController.m
//  SP2P
//
//  Created by 吴建东 on 16/6/6.
//  Copyright © 2016年 EIMS. All rights reserved.
//

#import "ExperienceViewController.h"
#import "ExperienceCell.h"
#import "ProgressLayer.h"
#import "ExperienceModel.h"
#import "PasswordView.h"
#import "TabViewController.h"

@interface ExperienceViewController ()<UITableViewDelegate,UITableViewDataSource,HTTPClientDelegate>
{
    ProgressLayer *_progressLayer;
    
    double _rewardBalance;
    NSString *_sign;
}
@property (weak, nonatomic  ) IBOutlet UITableView   *tableView;
@property (strong, nonatomic) IBOutlet UIView        *headerView;
@property (weak, nonatomic  ) IBOutlet UILabel       *rateValue;
@property (weak, nonatomic  ) IBOutlet ProgressLayer *layerView;
@property (weak, nonatomic  ) IBOutlet UILabel       *rateLabel;
@property (weak, nonatomic  ) IBOutlet UILabel       *profitDayLabel;
@property (weak, nonatomic  ) IBOutlet UILabel       *experienceValue;
@property (weak, nonatomic  ) IBOutlet UILabel       *experienceAmountLabel;
@property (weak, nonatomic  ) IBOutlet UILabel       *experienceAmountValue;
@property (strong, nonatomic) IBOutlet UIView        *footerView;
@property (weak, nonatomic  ) IBOutlet ClickButton   *tenderButton;
@property (weak, nonatomic  ) IBOutlet UITextField   *passwordtextField;

@property (nonatomic, strong) NetWorkClient  *requestClient;
@property (nonatomic, assign) BOOL           isLoading;
@property (nonatomic, assign) NSInteger      requestType;
@property (nonatomic, assign) NSInteger      currPage;
@property (nonatomic, assign) NSInteger      totalCount;
@property (nonatomic, strong) NSMutableArray *dataArray;

@end

@implementation ExperienceViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self setNavBarBackgroundColor:[UIColor clearColor] andStatusBar:UIStatusBarStyleLightContent];
    
    [self initNavBarTitle:@"" andLeftItemName:@"返回" andRightItemName:@""]; //新手体验

}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self setNavBarBackgroundColor:KColor andStatusBar:UIStatusBarStyleLightContent];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self initData];
    [self initView];
}

- (void)back {
    if (!_isFirstLogin) {
        [self.navigationController popViewControllerAnimated:YES];
    }else {
        [self dismissViewControllerAnimated:YES completion:nil];
        TabViewController *tabViewController = [[TabViewController alloc] init];
        tabViewController.selectedIndex = 3;
        AppDelegateInstance.window.rootViewController = tabViewController;
    }
}

#pragma mark - Action
- (IBAction)tenderButtonClick:(id)sender {

//    PasswordView *passwordView = [[PasswordView alloc] initWithFrame:RECTMAKE(0, 0, MSWIDTH, MSHIGHT)];
//    passwordView.originY = 0;
//    [passwordView show];
//    
//    return;
//    if (_passwordtextField.text.length <= 0) {
//        [SVProgressHUD showErrorWithStatus:@"请输入交易密码"];
//        return;
//    }
    
    [self tenderRequest];
}

- (void)textFieldValueChanged {
    
    return;
    if (_passwordtextField.text.length > 0) {
        [CommonClass buttonEnableWithButton:_tenderButton enable:YES];
    }else {
        [CommonClass buttonEnableWithButton:_tenderButton enable:NO];
    }
}

#pragma mark - TableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_dataArray.count) {
        static NSString *cellID = @"cellID";
        ExperienceCell *cell = [_tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [[NSBundle mainBundle] loadNibNamed:@"ExperienceCell" owner:self options:nil][0];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        [cell refreshCellWithModel:_dataArray[indexPath.row]];
        
        cell.frame=CGRectMake(cell.frame.origin.x, cell.frame.origin.y, cell.frame.size.width, KAdaptNum(112));
        return cell;
    }else {
        EmptyTableViewCell *cell = [[EmptyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"emptyCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.backgroundColor = KbackgroundColor;
        
        cell.frame=CGRectMake(cell.frame.origin.x, cell.frame.origin.y, cell.frame.size.width, _tableView.frame.size.height);
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self tableView:tableView cellForRowAtIndexPath:indexPath].frame.size.height;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [UIView viewWithFrame:RECTMAKE(0, 0, MSWIDTH, KAdaptNum(54)) backgroundColor:KbackgroundColor superview:nil];
    
    UIView *labelView = [UIView viewWithFrame:RECTMAKE(0, 10, MSWIDTH, GetHeight(headerView) - 10) backgroundColor:[UIColor whiteColor] superview:headerView];
    
    [UILabel labelWithFrame:RECTMAKE(10, 0, GetWidth(labelView) - 20, GetHeight(labelView)) text:@"体验金获得记录" textColor:KBlackColor textFont:14 fitWidth:NO superview:labelView];
    
    [UIView viewWithFrame:RECTMAKE(10, GetHeight(headerView) - kLineHeight, MSWIDTH - 10, kLineHeight) backgroundColor:KlayerBorder superview:headerView];
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return KAdaptNum(54);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 30.0f;
}

#pragma mark - Data
- (void)initData {
    _dataArray = [NSMutableArray array];
    
    [self requestData];
}
- (void)requestData {
    if (_isLoading) {
        [SVProgressHUD showImage:nil status:@"正在请求，请稍候再试..."];
        return;
    }
    _requestType = 1;
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@"514" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"id"];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters];
}

- (void)tenderRequest {
    if (_isLoading) {
        [SVProgressHUD showImage:nil status:@"正在请求，请稍候再试..."];
        return;
    }
    _requestType = 2;
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@"515" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"id"];
    [parameters setObject:_sign forKey:@"sign"];
    NSString *password = [NSString encrypt3DES:_passwordtextField.text key:DESkey];
    [parameters setObject:password forKey:@"dealpwd"];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters];
}

#pragma - 网络数据回调代理
- (void)startRequest {
    _isLoading = YES;
}

// 返回成功
- (void)httpResponseSuccess:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didSuccessWithObject:(id)obj {
    _isLoading = NO;
    [self hiddenRefreshView];
    NSDictionary *dics = obj;
     DLOG(@"dic=%@",dics);
    
    if ([[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]] isEqualToString:@"-1"]) {
        if (_requestType == 1) {
            _rewardBalance = [dics[@"rewardBalance"] doubleValue];
            [_progressLayer setPercent:75.0 animated:YES];
            if (dics[@"sign"]) {
                _sign = [NSString stringWithFormat:@"%@",dics[@"sign"]];
            }

            if (_rewardBalance > 0) {
                _rateLabel.text = [NSString stringWithFormat:@"%.1f",[[dics objectForKey:@"apr"] floatValue]];
                _profitDayLabel.text = [NSString stringWithFormat:@"可收益天数：%@天",[dics objectForKey:@"period"]];
                _experienceAmountLabel.text = [NSString stringWithFormat:@"%.0f元",_rewardBalance];
            }else {

                _rateLabel.text = [NSString stringWithFormat:@"%.1f",[[dics objectForKey:@"apr"] floatValue]];
                _profitDayLabel.text = [NSString stringWithFormat:@"可收益天数：%@天",[dics objectForKey:@"period"]];
                _experienceAmountLabel.text = [NSString stringWithFormat:@"%.0f元",_rewardBalance];
            }
            
            if (_currPage == 1) {
                [_dataArray removeAllObjects];
            }
            if (dics[@"detail"] && ![dics[@"detail"] isKindOfClass:[NSNull class]]) {
                NSDictionary *detail = dics[@"detail"];
                
            ExperienceModel *model = [ExperienceModel objectWithKeyValues:detail];
                model.expreienceId = [NSString stringWithFormat:@"%@",detail[@"id"]];
                model.getTime = [NSString converDate:[[detail objectForKey:@"time"] objectForKey:@"time"] withFormat:@"yyyy-MM-dd"];
                model.expiredTime = [NSString converDate:[[detail objectForKey:@"endTime"] objectForKey:@"time"] withFormat:@"yyyy-MM-dd"];
                model.status = detail[@"status"];
                _tenderButton.hidden = [model.status integerValue];
                
                [_dataArray addObject:model];
            }
            
            [_tableView reloadData];
        }else if (_requestType == 2) {
            [SVProgressHUD showSuccessWithStatus:[dics objectForKey:@"msg"]];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self back];
            });
        }
        
        
    }else if ([[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]] isEqualToString:@"-2"]) {
        
        [ReLogin outTheTimeRelogin:self];
    }else {
        
        [SVProgressHUD showImage:nil status:[dics objectForKey:@"msg"]];
    }
    
}

// 返回失败
- (void)httpResponseFailure:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didFailWithError:(NSError *)error {
    _isLoading = NO;
    [self hiddenRefreshView];
}

// 无可用的网络
- (void)networkError {
    //  [SVProgressHUD showErrorWithStatus:@"网络不给力，请检查您的网络设置"];
    _isLoading = NO;
    [self hiddenRefreshView];
}

#pragma mark - 刷新
- (void)headerRereshing {
    _currPage = 1;
    [self requestData];
}

- (void)footerRereshing {
    _currPage ++;
    [self requestData];
}

- (void)hiddenRefreshView {
    if (!_tableView.mj_header.hidden) {
        [_tableView.mj_header endRefreshing];
    }
    if (!_tableView.mj_footer.hidden) {
        [_tableView.mj_footer endRefreshing];
    }
}


#pragma mark - View
- (void)initView {
    _headerView.frame = RECTMAKE(0, 0, MSWIDTH, KAdaptNum(280));
    _footerView.frame = RECTMAKE(0, 0, MSWIDTH, KAdaptNum(100));
    _rateValue.font = KFontSize(10);
    _rateLabel.font = KFontSize(30);
    _profitDayLabel.font = KFontSize(12);
    _experienceAmountLabel.font = KFontSize(14);
    _experienceAmountValue.font = KFontSize(14);
    _tenderButton.titleLabel.font = KFontSize(15);
    
    [self loadLayerView];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.bounces = NO;
    self.tableView.estimatedRowHeight = KAdaptNum(112);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableHeaderView = self.headerView;
    self.tableView.tableFooterView = self.footerView;
    
    _tenderButton.clipsToBounds = YES;
    _tenderButton.layer.cornerRadius = kCornerRadius;
    _tenderButton.hidden = YES;
    [CommonClass buttonEnableWithButton:_tenderButton enable:YES];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldValueChanged) name:UITextFieldTextDidChangeNotification object:_passwordtextField];
}

- (void)loadLayerView {
    CGFloat progressWidth = KAdaptNum(120);
    
    _progressLayer = [[ProgressLayer alloc] initWithFrame:CGRectMake(0, 0, progressWidth, progressWidth) diameter:progressWidth roundWidth:5 start:CGPointMake(-210, 30)];
    [_layerView addSubview:_progressLayer];
    
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    _layerView.frame = RECTMAKE((MSWIDTH - KAdaptNum(120))/2, KAdaptNum(80), KAdaptNum(120), KAdaptNum(120));
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
